package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {
    @Autowired
    private CartInfoService cartInfoService;

    //加入商品到购物车
    @PostMapping("/addToCart/{skuId}/{skuNum}")
    public void addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum,
                          HttpServletRequest request){
        //获取真实或者临时用户地id
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            //临时用户ID
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart(skuId,skuNum,userId);
    }

    //查看购物车里面的内容
    @GetMapping("/toCart/{skuId}")
    public CartInfo toCart(@PathVariable Long skuId){
        return cartInfoService.toCart(skuId);
    }

    //初始化加入购物车集合,需要判断两种情况:有真实用户id和没有真实用户id
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        //获取真实用户id
        String userId = AuthContextHolder.getUserId(request);
        //获取临时用户id
        String userTempId = AuthContextHolder.getUserTempId(request);
        //查询购物车集合
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
        return Result.ok(cartInfoList);
    }

    //选中或者取消选中
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked,HttpServletRequest request){
        cartInfoService.checkCart(skuId,isChecked,request);
        return Result.ok();
    }

    //查询商品清单  查询购物车中已经选中的商品集合
    @GetMapping("/getCartInfoListByChecked")
    public List<CartInfo> getCartInfoListByChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.getCartInfoListByChecked(userId);
    }

}
